﻿using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;

namespace RssReader
{
  public partial class FeedItemDetailsPage : PhoneApplicationPage
  {
    string readMore = "";

    private const string FeedPublishKey = "FeedPublishKey";
    private const string FeedBody = "FeedBody";
    private const string FeedReadMore = "FeedReadMore";

    public FeedItemDetailsPage()
    {
      InitializeComponent();

      PageTransitionDetails.Completed += new EventHandler(PageTransitionDetails_Completed);

      SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
    }

    // Handle navigating back to content in the two frames
    private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
    {
      // Cancel default navigation
      e.Cancel = true;

      // Do page ransition animation
      PageTransitionDetails.Begin();
    }

    void PageTransitionDetails_Completed(object sender, EventArgs e)
    {
      // Reset root frame to MainPage.xaml
      PhoneApplicationFrame root = (PhoneApplicationFrame)Application.Current.RootVisual;
      root.GoBack();
      //NavigationService.GoBack();
    }

    private void StackPanel_Loaded(object sender, RoutedEventArgs e)
    {
      // Was thinking I could load the Description HTML text from the current record here :-)
      //webBrowser1.NavigateToString("" );
    }

    private void webBrowser1_Loaded(object sender, RoutedEventArgs e)
    {
      string t = "";

      readMore = WebBrowserHelper.GetBody(webBrowser1);

      if (readMore != null)
      {
        // Made use of a databound attached property but had to switch to the loaded event because
        // on Windows Phone 7 the webbrowser does not feature in the visual tree until the last moment.
        //readMore = WebBrowserHelper.GetBody(webBrowser1);
        t = "<b>" + tbTitle.Text + "</b><br /><br />" + tbDescription.Text;
      }
      else
      {
        if (true == PhoneApplicationService.Current.State.ContainsKey(FeedPublishKey))
        {
          DatePublishedTxtBx.Text = PhoneApplicationService.Current.State[FeedPublishKey] as string;
          t = PhoneApplicationService.Current.State[FeedBody] as string;
          readMore = PhoneApplicationService.Current.State[FeedReadMore] as string;
        }
      }

      //try to locate the phone number from previous save and simply override it   
      if (true == PhoneApplicationService.Current.State.ContainsKey(FeedPublishKey))
      {
        //clear prev value   
        PhoneApplicationService.Current.State.Remove(FeedPublishKey);
      }

      PhoneApplicationService.Current.State.Add(FeedPublishKey, DatePublishedTxtBx.Text);

      //try to locate the phone number from previous save and simply override it   
      if (true == PhoneApplicationService.Current.State.ContainsKey(FeedBody))
      {
        //clear prev value   
        PhoneApplicationService.Current.State.Remove(FeedBody);
      }

      PhoneApplicationService.Current.State.Add(FeedBody, t);

      //try to locate the phone number from previous save and simply override it   
      if (true == PhoneApplicationService.Current.State.ContainsKey(FeedReadMore))
      {
        //clear prev value   
        PhoneApplicationService.Current.State.Remove(FeedReadMore);
      }

      PhoneApplicationService.Current.State.Add(FeedReadMore, readMore);

      webBrowser1.NavigateToString(ConvertExtendedASCII(AddStyledBody(t)));

    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
      try
      {
        // Get the current item.Link value and cause IE to open to it.
        var task = new WebBrowserTask();
        task.URL = readMore;

        task.Show();
      }
      catch (Exception ex)
      {
        MessageBox.Show("The content is not accessible at this moment.", "Unable to access content", MessageBoxButton.OK);
      }
    }

    private string AddStyledBody(string content)
    {
      return "<html>" +
          "<head><style type=\"text/css\">a { color: #aaf;}</style></head>" +
          "<body style=\"background-color: black; color: white;\">" + content +
          "</body></html>";
    }

    /// <summary>
    /// use entity codes for any characters that are not in the standard ASCII set
    /// </summary>
    public static string ConvertExtendedASCII(string html)
    {
      string retVal = "";
      char[] s = html.ToCharArray();

      foreach (char c in s)
      {
        if (Convert.ToInt32(c) > 127)
          retVal += "&#" + Convert.ToInt32(c) + ";";
        else
          retVal += c;
      }

      return retVal;
    }


  }
}